<?php
// +----------------------------------------------------------------------
// | ThinkCMF [ WE CAN DO IT MORE SIMPLE ]
// +----------------------------------------------------------------------
// | Copyright (c) 2013-2017 http://www.thinkcmf.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: 老猫 <thinkcmf@126.com>
// +----------------------------------------------------------------------
namespace app\repair\controller;

use cmf\controller\HomeBaseController;
use app\repair\model\RepairCategoryModel;
use app\repair\service\PostService;
use app\repair\model\RepairPostModel;
use think\Db;


class ListController extends HomeBaseController
{

    public function index()
    {

        $img = Db::name('img')->find(4);
        $this->assign('img',$img);
        $id = input('id', 0, 'intval');

        $repairCategoryModel = new RepairCategoryModel();
        $category            = $repairCategoryModel->where('id', $id)->find();
       
        $listTpl = empty($category['list_tpl']) ? 'list' : $category['list_tpl'];
        // pre($listTpl,1);

        $this->assign('cat_id', $id);
        $this->assign('category', $category);
        
        $request = request();
        if( $request->isAjax() ){
            $html = $this->fetch($listTpl.'_ajax');
            
            $return = array(
                // 'error'     => 0,
                'data'      => $html,
                // 'start'     => $start,
                // 'size'      => $size,
                // 'more_data' => empty($more_data) ? 0 : 1 ,
            );
            return $return;
        }
        return $this->fetch('/' . $listTpl);
    }

    //故障维修添加
    public function add(){

        $img = Db::name('img')->find(4);
        $this->assign('img',$img);

        //如果是维修员，则不能申请故障维修
        $user_type = $this->user_type;
        if ($user_type == 'fix') {
            $this->error('您是维修人员，不能申请故障维修');
        }

        //分类
        $repairCategoryModel = new RepairCategoryModel();
        $category            = $repairCategoryModel->where('is_show', 1)->select();

        $this->assign('category', $category);
        // pre($category->toArray());die;

        //会员信息
        $member_id = cmf_get_current_user_id();  
        $user_info = $this->getUserInfo($member_id);

        $this->assign('user_info', $user_info);
        // pre($user_info);die;

        return $this->fetch('/add');
    }

    //添加提交
    public function addPost(){

        if ($this->request->isPost()) {
            $data   = $this->request->param();
            $post   = $data;

            //会员ID
            $post['member_id'] = cmf_get_current_user_id();

            //发布时间
            $post['published_time'] = date("Y-m-d H:i:s",time());

            $post['imgBase64'] = $post['img'];

            //审核状态
            $post['post_status'] = 99;
            $post['user_id'] = 1;

            // pre($post);die;

            //如果有上传图片
            if (!empty($post['imgBase64'])) {

                //定义图片数组
                $post['photos'] = array();
                $post['photo_urls'] = array();

                foreach ($post['imgBase64'] as $k => $v) {
                    header('Content-type:text/html;charset=utf-8');
                    $base64_image_content = $post['imgBase64'][$k];
                    //匹配出图片的格式
                    if (preg_match('/^(data:\s*image\/(\w+);base64,)/', $base64_image_content, $result)){
                        $type = $result[2];
                        $new_file = "upload/repair/".date('Ymd',time())."/";
                        if(!file_exists($new_file))
                        {
                            //检查是否有该文件夹，如果没有就创建，并给予最高权限
                            mkdir($new_file, 0777,true);
                        }
                        $new_file = $new_file.time().$k.".{$type}";

                        if (file_put_contents($new_file, base64_decode(str_replace($result[1], '', $base64_image_content)))){
                            // echo '新文件保存成功：', $new_file;
                            //循环把图片插入数组
                            array_push($post['photos'],$new_file);
                        }else{
                            // echo '新文件保存失败';
                            $this->error('上传图片失败！');
                        }
                    }
                }

                //组合数据格式
                $post['photos'] = $post['photos'];

                foreach ($post['photos'] as $kk => $vv) {
                    $post['photo_urls'][$kk] = str_replace('upload/', '', $vv);
                }

                foreach ($post['photos'] as $kk => $vv) {
                    $post['more']['photos'][$kk]['url'] = str_replace('upload/', '', $vv);
                    $post['more']['photos'][$kk]['name'] = str_replace('upload/repair/'.date('Ymd',time()).'/', '', $vv);
                }
            }

            unset($post['img']);

            //插入数据库
            $repairPostModel = new RepairPostModel();
            $res = $repairPostModel->allowField(true)->data($post, true)->isUpdate(false)->save();
            $repairPostModel->categories()->save($post['categoryId']);

            // $res = Db::name('repair_post')->insert($post);

            /*//排序号，按每个文类下文章的最大序号+1
            //获取当前分类下文章的最大排序号
            $maxListOrder  = db('repair_category_post')
                          -> where('category_id',$post['category_id'])
                          -> max('list_order');
            //最大排序号+1
            $maxListOrder += 1;     
            //更新的条件
            $where = [
                'post_id'     => $repairPostModel->id,
                'category_id' => $post['category_id'],
            ];
            //更新新增文章的排序号
            db('repair_category_post')->where($where)->update(['list_order'=>$maxListOrder]);*/

            if ($res) {
                $result = json_encode(array('msg'=>"提交成功",'status'=>1,'url'=>"http://".$_SERVER['HTTP_HOST'].url('myRepair')));
            }else{
                $result = json_encode(array('msg'=>"提交失败",'status'=>0));
            }
            echo $result; return;
        }
    }

    //我的故障列表
    public function myRepair(){
        $img = Db::name('img')->find(4);
        $this->assign('img',$img);
        
        $data = $this->request->param();

        //如果是维修管理员、则获取时间、派单状态
        $search_status = array(0=>'派单中',1=>'已派单',2=>'维修中',3=>'已完成',4=>'申请完成',5=>'拒绝完成');
        $this->assign('search_status',$search_status);

        //保存选择的派单状态
        if (isset($data['repair_status'])) {
            $repair_status['id'] = $data['repair_status'];
            $repair_status['name'] = $search_status[$data['repair_status']];
        }else{
            $repair_status['id'] = -1;
            $repair_status['name'] = "请选择";
        }
        $this->assign('repair_status',$repair_status);

        //保存选择的时间
        if (isset($data['appDate'])) {
            $appDate['year'] = $data['appDate'];
            $appDate['day']  = date('m-d', strtotime($data['appDate']));
            $appDate['week'] = mb_substr( "日一二三四五六",date("w",strtotime($data['appDate'])),1,"utf-8" );
        }else{
            $appDate['year'] = date('Y-m-d',time());
            $appDate['day']  = date('m-d',time());
            $appDate['week'] = mb_substr( "日一二三四五六",date("w"),1,"utf-8" );
        }
        $this->assign('appDate',$appDate);


        $member_id = cmf_get_current_user_id();
        $user_type = $this->user_type;
        //如果是维修人员
        $where = '';
        if ($user_type == 'fix') {
            $where = "repairman_id = ".$member_id;
        }elseif ($user_type == 'fix_admin') {  //如果是维修管理员
            if (isset($data['repair_status']) && $repair_status['id']>=0) {
                $where = "repair_status = ".$repair_status['id'];
            }else{
                $where = "1=1";
            }
            if (isset($data['appDate'])) {
                $where .= " and create_time > ".strtotime($data['appDate'])." and create_time < ".(strtotime($data['appDate']) + 86400);
            } 
        }else{
            $where = "member_id = ".$member_id;
        }

        // echo $where;

        //故障记录
        $repairPostModel = new RepairPostModel();
        $lists           = $repairPostModel->field('id,member_id,published_time,post_title,post_content,more,repair_place,repair_status,evaluate_status,repairman_id')->where($where)->order('id desc')->limit(5)->select()->toArray();

        //根据故障记录查询故障分类、提交故障的会员信息、维修人员信息
        $join = [
            ['repair_category_post cp', 'c.id = cp.category_id'],
        ];
        foreach ($lists as $k => $v) {
            //地点截取字符数
            $lists[$k]['repair_place'] = msubstr($lists[$k]['repair_place'],0,5);

            //分类信息
            $lists[$k]['category_info'] = Db::name('repair_category')->alias('c')->field('c.id,c.name')->join($join)->where("cp.is_show=1 and cp.post_id=".$v['id'])->find();

            //会员信息
            $lists[$k]['member_info'] = $this->getUserInfo($v['member_id']);
            $lists[$k]['member_info']['user_login'] = msubstr($lists[$k]['member_info']['user_login'],0,3);
            $lists[$k]['member_info']['department'] = msubstr($lists[$k]['member_info']['department'],0,5);

            //维修人员信息
            $lists[$k]['repairman_info'] = Db::name('member')->field('id,user_login')->where('id='.$v['repairman_id'])->find();

            //维修状态
            if ($v['repair_status']==0) {
                $lists[$k]['repair_status_text'] = "派单中";
            }elseif ($v['repair_status']==1) {
                //如果是普通会员
                $lists[$k]['repair_status_text'] = "维修中";
                //如果是维修人员（待完善）

            }elseif ($v['repair_status']==2) {
                $lists[$k]['repair_status_text'] = "维修中";                
            }elseif ($v['repair_status']==3) {
                $lists[$k]['repair_status_text'] = "已完成";                
            }elseif ($v['repair_status']==4) {
                //如果是维修人员或维修管理员
                if ($user_type == 'fix' or $user_type == 'fix_admin') {
                    $lists[$k]['repair_status_text'] = "申请中";
                }else{
                    $lists[$k]['repair_status_text'] = "维修中";    
                }            
            }elseif ($v['repair_status']==5) {
                if ($user_type == 'fix' or $user_type == 'fix_admin') {
                    $lists[$k]['repair_status_text'] = "拒绝完成";
                }else{
                    $lists[$k]['repair_status_text'] = "维修中";    
                }                 
            }

            //会员类别,如果是维修会员则前端不显示维修人员信息
            $lists[$k]['user_type'] = $user_type;
        }

        $this->assign('lists', $lists);
        $this->assign('user_type', $user_type);
        $this->assign('lists_count', count($lists));

        // pre($lists);die;
        return $this->fetch('/myRepair');
    }

    //ajax加载更多，查询该分类下的文章
    public function listAjax(){
        $start    = input('start',0,'intval');
        $size     = input('size',0,'intval');
        $repair_status = input('repair_status','','intval');
        $appDate = input('appDate','');

        //判断会员属于普通会员还是维修员（待完善）
        $member_id = cmf_get_current_user_id();
        $user_type = $this->user_type;
        //如果是维修人员
        $where = '';
        if ($user_type == 'fix') {
            $where = "repairman_id = ".$member_id;
        }elseif ($user_type == 'fix_admin') {
            if ($repair_status>=0) {
                $where = "repair_status = ".$repair_status;
            }else{
                $where = "1=1";
            }
            if ($appDate) {
                $where .= " and create_time > ".strtotime($appDate)." and create_time < ".(strtotime($appDate) + 86400);
            }
        }else{
            $where = "member_id = ".$member_id;
        }

        //故障记录
        $repairPostModel = new RepairPostModel();
        $lists           = $repairPostModel->field('id,member_id,published_time,post_title,repair_place,repair_status,repairman_id')->where($where)->order('id desc')->select()->toArray();

        //根据故障记录查询故障分类、提交故障的会员信息、维修人员信息
        $join = [
            ['repair_category_post cp', 'c.id = cp.category_id'],
        ];
        foreach ($lists as $k => $v) {
            //地点截取字符数
            $lists[$k]['repair_place'] = msubstr($lists[$k]['repair_place'],0,5);

            //分类信息
            $lists[$k]['category_info'] = Db::name('repair_category')->alias('c')->field('c.id,c.name')->join($join)->where("cp.is_show=1 and cp.post_id=".$v['id'])->find();

            //会员信息
            $lists[$k]['member_info'] = $this->getUserInfo($v['member_id']);
            $lists[$k]['member_info']['user_login'] = msubstr($lists[$k]['member_info']['user_login'],0,3);
            $lists[$k]['member_info']['department'] = msubstr($lists[$k]['member_info']['department'],0,5);

            //维修人员信息
            $lists[$k]['repairman_info'] = Db::name('member')->field('id,user_login')->where('id='.$v['repairman_id'])->find();

            //维修状态
            if ($v['repair_status']==0) {
                $lists[$k]['repair_status_text'] = "派单中";
            }elseif ($v['repair_status']==1) {
                $lists[$k]['repair_status_text'] = "维修中";
            }elseif ($v['repair_status']==4) {
                //如果是维修人员或维修管理员
                if ($user_type == 'fix' or $user_type == 'fix_admin') {
                    $lists[$k]['repair_status_text'] = "申请中";
                }else{
                    $lists[$k]['repair_status_text'] = "维修中";    
                }            
            }elseif ($v['repair_status']==5) {
                if ($user_type == 'fix' or $user_type == 'fix_admin') {
                    $lists[$k]['repair_status_text'] = "拒绝完成";
                }else{
                    $lists[$k]['repair_status_text'] = "维修中";    
                }                 
            }

            //会员类别,如果是维修会员则前端不显示维修人员信息
            $lists[$k]['user_type'] = $user_type;
        }

        // pre($lists);die;

        //没有数据
        /*if( count($lists) < 1 ){
            $return = array(
                'error'   => 1,
            );
            return $return;
        }*/
        
        // pre($lists);die;
        return $lists;
    }

    //故障详情页面
    public function repair_detail(){

        $img = Db::name('img')->find(4);
        $this->assign('img',$img);
        $id = input('id', 0, 'intval');

        //判断会员属于普通会员还是维修员
        $member_id = cmf_get_current_user_id();

        $msg_id = $this->request->param('msg_id', 0, 'intval');
        if (!empty($msg_id)) {
            $res = Db::name('new_msg_user')->where(['user_id'=>$member_id,'msg_id'=>$msg_id])->find();
            if(!$res){
                Db::name('new_msg_user')->insert(['user_id'=>$member_id,'msg_id'=>$msg_id]);
            }
        }
        $user_type = $this->user_type;
        $this->assign('user_type',$user_type);

        if ($user_type != 'fix_admin') {
            $where = ' and (member_id='.$member_id.' or repairman_id='.$member_id.')';
        }
        $repair_info = Db::name('repair_post')->where('id='.$id.$where)->find();


        //判断是否可查看该故障单
        if (empty($repair_info)) {
            $this->error('非法操作');
        }

        //内容转实体
        $repair_info['post_content'] = html_entity_decode($repair_info['post_content']);

        //json格式图片转换为数组
        $repair_info['img'] = json_decode($repair_info['more'],true);

        $join = [
            ['repair_category_post cp', 'c.id = cp.category_id'],
        ];
        //分类信息
        $repair_info['category_name'] = Db::name('repair_category')->alias('c')->join($join)->where("cp.is_show=1 and cp.post_id=".$repair_info['id'])->value('c.name');

        //会员信息
        $repair_info['member_info'] = $this->getUserInfo($repair_info['member_id']);

        //维修人员信息
        $repair_info['repairman_info'] = Db::name('member')->field('id,user_login,mobile')->where('id='.$repair_info['repairman_id'])->find();


        //维修状态
        if ($repair_info['repair_status']==0) {
            $repair_info['repair_status_text'] = "派单中";
        }elseif ($repair_info['repair_status']==1) {
            $repair_info['repair_status_text'] = "维修中";
        }elseif ($repair_info['repair_status']==2) {
            $repair_info['repair_status_text'] = "维修中";                
        }elseif ($repair_info['repair_status']==3) {
            $repair_info['repair_status_text'] = "已完成";                
        }elseif ($repair_info['repair_status']==4) {
                //如果是维修人员或维修管理员
                if ($user_type == 'fix' or $user_type == 'fix_admin') {
                    $repair_info['repair_status_text'] = "申请中";
                }else{
                    $repair_info['repair_status_text'] = "维修中";    
                }            
            }elseif ($repair_info['repair_status']==5) {
                if ($user_type == 'fix' or $user_type == 'fix_admin') {
                    $repair_info['repair_status_text'] = "拒绝完成";
                }else{
                    $repair_info['repair_status_text'] = "维修中";    
                }                 
            }

        // pre($repair_info);die;
        $this->assign('repair_info',$repair_info);
        return $this->fetch('/repair_detail');

    }

    //异步评价满意度
    public function ajaxEvaluate(){

        $repair_id = input('repair_id', 0, 'intval');
        $evaluate_status = input('evaluate_status', 0, 'intval');

        $member_id = cmf_get_current_user_id(); //当前会员ID

       //判断评价的故障单是否属于当前会员的
        $repair_count = Db::name('repair_post')->where('id='.$repair_id.' and member_id='.$member_id.' and repair_status=3 and evaluate_status=0')->count();

        if ($repair_count) {
            //更改评价状态
            $result = Db::name('repair_post')->where('id='.$repair_id)->update(['evaluate_status'=>$evaluate_status]);
            if ($result) {
                echo json_encode(array('msg'=>'评价成功','error'=>0,'url'=>'/repair/list/myRepair'));
                return;
            }
        }else{
            echo json_encode(array('msg'=>'非法操作','error'=>1,'url'=>'/repair/list/repair_detail/id/'.$repair_id));
            return;
        }
        // pre($repair_count);die;
    }

    //填写维修单页面
    public function add_repair(){
        $img = Db::name('img')->find(4);
        $this->assign('img',$img);
        $id = input('id', 0, 'intval');

        //判断会员属于普通会员还是维修员（待完善）
        $member_id = cmf_get_current_user_id();
        $user_type = Db::name('member')->where('id='.$member_id)->value('user_type');
        $this->assign('user_type',$user_type);

        $repair_info = Db::name('repair_post')->where('id='.$id.' and repairman_id='.$member_id)->find();
        $repair_info['repair_place'] = msubstr($repair_info['repair_place'],0,6);
        //判断是否可查看该故障单
        if (empty($repair_info)) {
            $this->error('非法操作');
        }

        $join = [
            ['repair_category_post cp', 'c.id = cp.category_id'],
        ];
        //分类信息
        $repair_info['category_name'] = Db::name('repair_category')->alias('c')->join($join)->where("cp.is_show=1 and cp.post_id=".$repair_info['id'])->value('c.name');

        //会员信息
        $repair_info['member_info'] = $this->getUserInfo($repair_info['member_id']);
        $repair_info['member_info']['user_login'] = msubstr($repair_info['member_info']['user_login'],0,3);
        $repair_info['member_info']['department'] = msubstr($repair_info['member_info']['department'],0,5);

        // pre($repair_info);die;

        $this->assign('repair_info',$repair_info);
        $this->assign('id',$id);
        return $this->fetch('/add_repair');
    }

    //提交维修单
    public function addRepairPost(){

        if ($this->request->isPost()) {
            $data   = $this->request->param();
            $post   = $data;

            //维修人员ID
            $post['repairman_id'] = cmf_get_current_user_id();

            $post['repair_id'] = $data['repair_id'];

            $data['imgBase64'] = $data['img'];

            //判断是否合法
            $user_type = $this->user_type;  //会员角色
            $is_have = Db::name('repair_post')->where('id='.$post['repair_id'].' and repairman_id='.$post['repairman_id'])->count();
            if (!$is_have or $user_type!='fix') {
                $this->error('非法操作');
            }

            //发布时间
            $post['published_time'] = time();
            $post['create_time'] = time();

            //审核状态
            $post['post_status'] = 99;
            $post['user_id'] = 1;

            //维修状态
            $post['repair_status'] = 4;

            $post['post_content'] = $data['post_content'];


            //如果有上传图片
            if (!empty($data['imgBase64'])) {

                //定义图片数组
                $post['more'] = '';
                $data['photo_urls'] = array();

                foreach ($data['imgBase64'] as $k => $v) {
                    header('Content-type:text/html;charset=utf-8');
                    $base64_image_content = $data['imgBase64'][$k];
                    //匹配出图片的格式
                    if (preg_match('/^(data:\s*image\/(\w+);base64,)/', $base64_image_content, $result)){
                        $type = $result[2];
                        $new_file = "upload/repair/".date('Ymd',time())."/";
                        if(!file_exists($new_file))
                        {
                            //检查是否有该文件夹，如果没有就创建，并给予最高权限
                            mkdir($new_file, 0700);
                        }
                        $new_file = $new_file.time().$k.".{$type}";

                        if (file_put_contents($new_file, base64_decode(str_replace($result[1], '', $base64_image_content)))){
                            $post['more'] .= $new_file.'|';
                        }else{
                            $this->error('上传图片失败！');
                        }
                    }
                }

                //处理图片字符串格式
                $post['more'] = rtrim($post['more'],'|');
            }

            unset($post['img']);

            // pre($post);die;
            //查询是否已有提交过完成单
            $is_complete = Db::name('repair_order')->where('repair_id='.$post['repair_id'])->find();
            if ($is_complete) {
                //修改完成单
                $res = Db::name('repair_order')->where('repair_id='.$post['repair_id'])->update($post);

            }else{
                //插入完成单
                $res = Db::name('repair_order')->insert($post);
            }
             
            if ($res) {
                Db::name('repair_post')->where('id='.$post['repair_id'])->update(['repair_status'=>4]);
            }

            if ($res) {
                $result = json_encode(array('msg'=>"提交成功",'status'=>1,'url'=>"http://".$_SERVER['HTTP_HOST'].url('myRepair')));
            }else{
                $result = json_encode(array('msg'=>"提交失败",'status'=>0));
            }
            echo $result; return;

        }


    }


    //获取当前会员信息
    public function getUserInfo($member_id){

        $join = [
            ['wechat_department_user u','m.openid = u.user_id','LEFT'],
            ['wechat_department d','d.id = u.department_id','LEFT'],
            ['wechat_tag_user t','m.id = t.userid','LEFT'],
            ['wechat_tag wt','t.tagid = wt.tagid','LEFT'],
        ];
        $user_info = Db::name('member')->alias('m')->field('m.*,d.name as department,wt.tagname')->join($join)->where('m.id='.$member_id)->find();

        return $user_info;
    }

    
}
